import AuthComponent from '@/components/Authorized/AuthComponent';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Menu, message, Modal, Select, DatePicker, Input } from 'antd';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';

import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { getInfoTable, addData, handleUpdateData, removeData, queryCityInfo } from './service';

import moment from 'moment';
import styles from './index.less';

const { confirm } =Modal
const { Option } = Select;

const OversaleInfoTable = (props) => {

  const { data: selectData } = useRequest(queryCityInfo);
  const [createModalVisible, handleCreateModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [updateData, saveUpdateData] = useState({})

  const actionRef = useRef();
  const ref = useRef();
  const searchRef = useRef();

  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 360);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse])


  const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }

  const columns = [
    {
      title: '航班号',
      dataIndex: 'flightNum',
      width: 90,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input 
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 120,
      hideInSearch: true
    },
    {
      title: '航班起始日期',
      dataIndex: 'flightDateStart',
      hideInTable: true,
      order: 4,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      dataIndex: 'flightDateEnd',
      hideInTable: true,
      order: 4,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '起始航站',
      dataIndex: 'airportS',
      width: 120,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '到达航站',
      dataIndex: 'airportE',
      width: 120,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '可提供座位数',
      dataIndex: 'seatCountDesc',
      hideInSearch: true,
      width: 150
    },
    {
      title: '预计超售',
      dataIndex: 'plancount',
      hideInSearch: true,
      width: 120
    },
    {
      title: '系统服务实超人数',
      dataIndex: 'systemActCount',
      hideInSearch: true,
      width: 180
    },
    {
      title: '系统服务实超补偿金额',
      dataIndex: 'systemActAmount',
      hideInSearch: true,
      width: 180
    },
    {
      title: '预超更新人',
      dataIndex: 'plancountUpdatorId',
      hideInSearch: true,
      width: 160
    },
    {
      title: '预超更新时间',
      dataIndex: 'plancountUpdateTime',
      hideInSearch: true,
      width: 160
    },
    {
      title: '实际超售',
      dataIndex: 'actcount',
      hideInSearch: true,
      width: 120
    },
    {
      title: '实超更新人',
      dataIndex: 'updateUserId',
      hideInSearch: true,
      width: 160
    },
    {
      title: '实超更新时间',
      dataIndex: 'updateTime',
      hideInSearch: true,
      width: 160
    },
    {
      title: '补偿金额',
      dataIndex: 'amountPaid',
      hideInSearch: true,
      width: 120
    },
    {
      title: '旅客处理情况',
      dataIndex: 'note',
      hideInSearch: true,
      width: 160
    },
  ];

  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列

  const tableSelectChange = (selectedRowKeys, selectedRows) =>{
    handleSelectedRowKeys(selectedRowKeys)
    handleSelectedRows(selectedRows)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange
  };

  // 获取列表详情方法
  const beforeSearchSubmit = useCallback(params => {
    params['flightDateStart'] = params.flightDateStart ? params.flightDateStart.format('YYYY-MM-DD') : '';
    params['flightDateEnd'] = params.flightDateEnd ? params.flightDateEnd.format('YYYY-MM-DD') : '';

    if (!isCollapse) {
      return { ...params}
    } else {
      if (event && event.target && event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('flightDateStart') === -1) {
          params.flightDateStart = ''
        }
        if (Object.keys(params).indexOf('flightDateEnd') === -1) {
          params.flightDateEnd = ''
        }
      } else if (event && event.target && event.target.querySelector && event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          flightDateStart: moment(),
          flightDateEnd: moment()
        })
      }
      return { ...params }
    }
  }, []);
  // 新增保存
  const handleAdd = async fields => {
    const hide = message.loading('正在添加');
    try {
      let res = await addData({...fields});
      if (res.code === '0') {
        hide();
        message.success('添加成功');
        return true
      } else {
        hide()
      }
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };
  // 编辑保存
  const handleUpdate = async fields => {
    const hide = message.loading('正在更新');
    try {
      let res = await handleUpdateData(fields);
      if (res.code === '0') {
        hide();
        message.success('更新成功');
        return true
      } else {
        hide()
      }
    } catch (error) {
      hide();
      message.error('更新失败请重试！');
      return false;
    }
  };
  //删除
  const handleRemove = async (selectedRows) => {
      try {
        await removeData({
          ids: selectedRows.map(row => row.id).toString(),
        });
        message.success('删除成功，即将刷新');
        return true;
      } catch (error) {
        message.error('删除失败，请重试');
        return false;
      }

  };
  return (
    <div>
      <ProTable
        headerTitle="超售信息"
        className={ `${styles.oversaleInfoTable} rest-pro-table-form-compact`}
        actionRef={actionRef}
        formRef={ref}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        rowKey="id"
        size='small'
        scroll={{ x: 1200, y: height }}
        dateFormatter="YYYY-MM-DD"
        rowSelection={
          (AuthComponent.getAuth('usualMonitor.oversaleInfo.edit') ||
          AuthComponent.getAuth('usualMonitor.oversaleInfo.delete'))
          ? rowSelection
          : false
        }
        rowSelection={rowSelection}
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode="usualMonitor.oversaleInfo.add">
            <Button icon='plus' type="primary" onClick={() => handleCreateModalVisible(true)}>
              新建
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="usualMonitor.oversaleInfo.edit">
            <Button icon='edit' onClick={() => {
              if (selectedRowKeys.length > 1) {
                message.error('只能选择一条进行编辑')
              } else if (selectedRowKeys.length === 0) {
                message.error('请选择编辑的条目')
              } else {
                saveUpdateData(selectedRows[0])
                handleUpdateModalVisible(true)
              }
              }}>
              编辑
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="usualMonitor.oversaleInfo.delete">
            <Button 
              icon='delete'
              selectedKeys={[]}
              onClick={ () => {
                if (selectedRowKeys.length === 0) {
                  message.error("请选择删除的条目")
                } else {
                  confirm({
                    title: '提示',
                    content: '确认操作后该超售数据将被删除，无法使用，你还要继续吗？',
                    cancelText: '取消',
                    okText: '确认',
                    onOk: async () => {
                      let res = await handleRemove(selectedRows)
                      if (res) {
                        actionRef.current.reload();
                        handleSelectedRows([])
                        handleSelectedRowKeys([])
                      }
                    }
                  })
                }
              }}
            >
              删除
            </Button>
          </AuthComponent>
        ]}
        search={{
          searchText: (
            <span ref={searchRef} href>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val);
          }
        }}
        beforeSearchSubmit={beforeSearchSubmit}
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        request={params => {
          if (!params['flightDateStart'] && !params['flightDateEnd']) {
            params['flightDateStart'] = moment().format('YYYY-MM-DD');
            params['flightDateEnd'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              flightDateStart: moment(),
              flightDateEnd: moment()
            })
          }
          // if (!params['airportS']) {
          //   ref.current.setFieldsValue({
          //     airportS: ''
          //   })
          // }
          // if (!params['airportE']) {
          //   ref.current.setFieldsValue({
          //     airportE: ''
          //   })
          // }
          return getInfoTable({...params})
        }}
        tableAlertRender={() => {
          return false
        }}
        columns={columns}
      />
      <CreateForm
        onSubmit={async value => {
          let params = value
          params.flightDate = params.flightDate ? params.flightDate.format('YYYY-MM-DD'): ''
          const success = await handleAdd(params);
          if (success) {
            handleCreateModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleCreateModalVisible(false)}
        createModalVisible={createModalVisible}
      />

      <UpdateForm
        onSubmit={async value => {
          let params = value
          const success = await handleUpdate(params);
          if (success) {
            handleUpdateModalVisible(false);
            handleSelectedRows([])
            handleSelectedRowKeys([])
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleUpdateModalVisible(false)}
        updateModalVisible={updateModalVisible}
        updateData={updateData}
      />
    </div>
  );
};

export default Form.create()(OversaleInfoTable);
